package com.yhq.oj.judge.sandbox.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.yhq.oj.common.ErrorCode;
import com.yhq.oj.exception.BusinessException;
import com.yhq.oj.judge.sandbox.CodeSandBox;
import com.yhq.oj.judge.sandbox.model.ExcuteCodeRequest;
import com.yhq.oj.judge.sandbox.model.ExcuteCodeResponse;
import org.apache.commons.lang3.StringUtils;

import static com.yhq.oj.utils.SignUtils.genSign;

/**
 * @program: oj-backend
 * @description: 远程代码沙箱实现类
 * @author: HenryYang
 * @create: 2023-08-23 15:36
 **/
public class RemoteCodeSandBoxImpl implements CodeSandBox {
    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String SECRET_KEY = "secretKey";
    @Override
    public ExcuteCodeResponse excuteCode(ExcuteCodeRequest excuteCodeRequest){
        System.out.println("第三方代码沙箱");
        //8090为代码沙箱 端口
        String url = "http://localhost:8090/execute";
        try {
            String json = JSONUtil.toJsonStr(excuteCodeRequest);
            String sign = genSign(json, SECRET_KEY);
//            System.out.println(json);
            String httpResponse = HttpUtil.createPost(url)
                    .header(AUTH_REQUEST_HEADER,sign)
                    .body(json)
                    .execute()
                    .body();
            if(StringUtils.isBlank(httpResponse)){
                throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remoteCodesanbox error"+ httpResponse);
            }
            return JSONUtil.toBean(httpResponse,ExcuteCodeResponse.class);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("在执行将请求参数转为JSON字符串时出错");
            return null;
        }

    }
}